package com.yjw.demo.pattern.singleton2;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ContainerSingleton {
    // 私有的构造方法
    private ContainerSingleton(){}
 
    // 存储实例的map,ConcurrentHashMap中线程安全，spring框架的IOC注册中心就是用这种方式实现的
    private static Map<String,Object> ioc = new ConcurrentHashMap<String,Object>();
 
    public static Object getBean(String className){
        synchronized (ioc){
            //如果map中没有这个class实例
            if(!ioc.containsKey(className)){
                Object obj = null;
                try {
                    obj = Class.forName(className).newInstance();
                    ioc.put(className, obj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return obj;
            }
            else
                return ioc.get(className);
        }
    }
}